package com.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class BrowserSimulationUtil {
	// 默认浏览器
	private static String DEFAULTBROWSERTYPE = "IE";
	// 默认编码
	private static String DEFAULTENCODE = "UTF-8";
	//会话session
	private static String sessionID = "" ;
	
	private HttpResponse response;//用途
	private DefaultHttpClient httpClient = new DefaultHttpClient();//一直使用的客户端
	
	public void login(String url, HashMap<String, String> paramMap){
		HttpPost httpost = new HttpPost(url);

		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("method", "post"));
		Set<String> set = paramMap.keySet();
		for (Iterator<String> it = set.iterator(); it.hasNext();) {
			String key = it.next();
			String value = paramMap.get(key);
			
			nvps.add(new BasicNameValuePair(key, value));
		}
		
		try {
			httpost.setEntity(new UrlEncodedFormEntity(nvps, DEFAULTENCODE)); 
			
			response = httpClient.execute(httpost);//执行登录请求 返回信息
			
//			response.
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace() ;
		} finally {
			httpost.abort();// 不废除会报错
		}
	}
	
	public void submit(){
		
	}

	/**
	 * 模拟浏览器提交
	 * 
	 * @param url
	 *            提交url
	 * @param paramMap
	 *            提交参数
	 */
	public static void simulationSubmit(String formURL, HashMap<String, String> paramMap) throws Exception {
		URL url = new URL(formURL);
		HttpURLConnection huc = (HttpURLConnection) url.openConnection();
		// 设置允许output
		huc.setDoOutput(true);
		// 设置为post方式
		huc.setRequestMethod("POST");
		huc.setRequestProperty("Cookie", sessionID);
		StringBuffer sb = new StringBuffer("a=1");
		
		Set<String> set = paramMap.keySet();
		for (Iterator<String> it = set.iterator(); it.hasNext();) {
			String key = it.next();
			String value = paramMap.get(key);
			
			sb.append("&" + key + "=" + value);
		}

		OutputStream os = huc.getOutputStream();
		os.write(sb.toString().getBytes(DEFAULTENCODE));
		os.close();
		
		BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream())) ;
		
		huc.connect();
		
		//打印请求头信息
        Map<String, List<String>> hfs = huc.getHeaderFields();
        Set<String> keys=hfs.keySet();
        for(String str : keys){
            List<String> vs = hfs.get(str);
            System.out.print(str + ":");
            for(String v : vs){
                System.out.print(v+"\t");
            }
            System.out.println();
        }

        if(sessionID.equals("")) {
	        String cookieValue=huc.getHeaderField("Set-Cookie");
	        sessionID = cookieValue.substring(0, cookieValue.indexOf(";"));
        }
		String line = br.readLine();
		while (line != null) {
//			System.out.println(line);
			line = br.readLine();
		}
		
		System.out.println();
	}
	
	public static void main(String[] args) {
		try {
			HashMap<String, String> map = new HashMap<String, String>() ;
			map.put("code", "-100") ;
			map.put("paramMap.logColumn", "s_userLoginAccount,currentDate") ;
			map.put("paramMap.account", "admin") ;
			map.put("paramMap.password", "admin123") ;
			simulationSubmit("http://192.168.12.199:9000/ccbm/loginAction.action", map) ;
			System.out.println("" + sessionID);
			
			map = new HashMap<String, String>() ;
			map.put("code", "001003008") ;
			map.put("name", "paramMap.logColumn") ;
			map.put("paramMap.userStatus", "0") ;
			map.put("paramMap.userID", "1295071954838") ;
			
			simulationSubmit("http://192.168.12.199:9000/ccbm/operateAction.action", map) ;
			
//			BrowserSimulationUtil bs = new BrowserSimulationUtil() ;
//			bs.login("http://192.168.12.199:9000/ccbm/loginAction.action", map) ;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
